<template>
  <el-dialog v-model="dialogVisible" title="更新提示" width="500">
    <template v-if="!downloaded">
      <span v-if="!downloadLoading">发现新版本{{ version }}是否下载？</span>
      <el-progress
        v-else
        :percentage="progress"
        :stroke-width="15"
        striped
        striped-flow
        :duration="10"
      />
    </template>
    <span v-else>下载完成，立即重启应用？</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button :disabled="downloadLoading" @click="dialogVisible = false">暂不</el-button>
        <el-button :loading="downloadLoading" type="primary" @click="confirm">
          {{ downloadLoading ? '下载中' : '确定' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'

onMounted(async () => {
  await window.electron.ipcRenderer.invoke('check-updates')
})

const dialogVisible = ref(false)
window.electron.ipcRenderer.on('update-available', (event, obj) => {
  version.value = obj.version
  dialogVisible.value = true
})

let i = 0
window.electron.ipcRenderer.on('update-not-available', () => {
  if (i > 0) {
    ElMessage({
      message: '已是最新版本',
      offset: 50
    })
  }
  i++
})

const downloadLoading = ref(false)
function confirm() {
  if (downloaded.value) {
    window.electron.ipcRenderer.invoke('restart-app')
    dialogVisible.value = false
    return
  }
  downloadLoading.value = true
  window.electron.ipcRenderer.invoke('start-download')
}

window.electron.ipcRenderer.on('download-progress', (event, progres) => {
  progress.value = Number(progres.percent).toFixed(2)
})

const downloaded = ref(false)
window.electron.ipcRenderer.on('update-downloaded', () => {
  dialogVisible.value = true
  downloaded.value = true
  downloadLoading.value = false
})

const progress = ref()
const version = ref()
</script>
<style lang="scss" scoped></style>
